//
//  XMCameraController.m
//  XiaoMiao
//
//  Created by 23 on 2018/1/28.
//  Copyright © 2018年 smallyou. All rights reserved.
//

#import "XMCameraController.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "XMAlbumScanController.h"
#import "XMAlbumScrollView.h"
#import <Photos/Photos.h>
#import "UIImage+Rotate.h"
#import "UIImage+SubImage.h"
#import "TZImagePickerController.h"

@interface XMCameraController () <AVCaptureMetadataOutputObjectsDelegate, AVCaptureVideoDataOutputSampleBufferDelegate>

//捕获设备，通常是前置摄像头，后置摄像头，麦克风（音频输入）
@property (nonatomic, strong) AVCaptureDevice *device;
//AVCaptureDeviceInput 代表输入设备，他使用AVCaptureDevice 来初始化
@property (nonatomic, strong) AVCaptureDeviceInput *input;
//输出图片
@property (nonatomic ,strong) AVCaptureStillImageOutput *imageOutput;
//session：由他把输入输出结合在一起，并开始启动捕获设备（摄像头）
@property (nonatomic, strong) AVCaptureSession *session;
//图像预览层，实时显示捕获的图像
@property (nonatomic ,strong) AVCaptureVideoPreviewLayer *previewLayer;
/**AVCaptureConnection *connection*/
@property(nonatomic,strong) AVCaptureConnection *connection;

/**标准图*/
//@property(nonatomic,weak) UIImageView *standardImageView;
@property(nonatomic,weak) XMAlbumScrollView *standardImageView;
/**摄像占位视图*/
@property(nonatomic,weak) UIView *contentView;
/**成像后的图片*/
//@property(nonatomic,weak) UIImageView *outImageView;
@property(nonatomic,weak) XMAlbumScrollView *outImageView;

/**返回按钮*/
@property(nonatomic,weak) UIButton *backButton;
/**切换摄像头*/
@property(nonatomic,weak) UIButton *changeButton;
/**拍照按钮*/
@property(nonatomic,weak) UIButton *takePhotoButton;
/**相册按钮*/
@property(nonatomic,weak) UIButton *albumButton;
/**手电筒按钮*/
@property(nonatomic,weak) UIButton *flashlightButton;
@end

@implementation XMCameraController

- (void)viewDidLoad {
    [super viewDidLoad];

    MJWeakSelf
    [AppGlobal isCameraDeviceAvalableSureBlock:^{
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }];
    
    
    //设置UI
    [self setupUI];
    
    //创建扫描设备
    [self setupCapture];
    


    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [UIApplication sharedApplication].statusBarHidden = YES;
    self.navigationController.navigationBar.hidden = YES;
    
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    self.previewLayer.frame = self.contentView.layer.bounds;
    
    //添加标准线
    [self addGrid:self.view];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].statusBarHidden = NO;
    self.navigationController.navigationBar.hidden = NO;
    
    //强制竖屏
//    self.view.transform = CGAffineTransformIdentity;
}


#pragma mark - UI
- (void)setupUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    //标准图
    XMAlbumScrollView *standardImageView = [[XMAlbumScrollView alloc] init];
    standardImageView.backgroundColor = [UIColor whiteColor];
    XMAlbumScanModel *imageModel = [[XMAlbumScanModel alloc] init];
    imageModel.imageUrl = self.standrandImageUrl;
    UIImage *placeholderImg = self.standrandImage;
    if (placeholderImg == nil) {
        placeholderImg = [UIImage imageNamed:@"photoPlaceHoder"];
        [placeholderImg rotate:UIImageOrientationLeft];
    }
    imageModel.image = placeholderImg;
    standardImageView.imageModel = imageModel;
    standardImageView.isStandard = YES;
    
    WEAKSELF
    standardImageView.callback = ^(CGFloat zoom, CGPoint offset) {
        weakSelf.outImageView.zoom = zoom;
        weakSelf.outImageView.offset = offset;
    };
    [self.view addSubview:standardImageView];
    self.standardImageView = standardImageView;
    self.standardImageView.imageView.contentMode = UIViewContentModeScaleAspectFit;
    
    //占位视图
    UIView *contentView = [[UIView alloc] init];
    [self.view addSubview:contentView];
    self.contentView = contentView;
    
    //成像后的显示视图
//    UIImageView *outImageView = [[UIImageView alloc] init];
    XMAlbumScrollView *outImageView = [[XMAlbumScrollView alloc] init];
//    outImageView.contentMode = UIViewContentModeScaleAspectFill;
    outImageView.backgroundColor = [UIColor whiteColor];
    outImageView.hidden = YES;
    outImageView.layer.masksToBounds = YES;
    outImageView.callback = ^(CGFloat zoom, CGPoint offset) {
        weakSelf.standardImageView.zoom = zoom;
        weakSelf.standardImageView.offset = offset;
    };
    [self.contentView addSubview:outImageView];
    self.outImageView = outImageView;
    
    //返回按钮
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setImage:[UIImage imageNamed:@"ic_common_arrow_back_black"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(actionBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
    self.backButton = backButton;
    
    //切换摄像头视图
    UIButton *changeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [changeButton setImage:[UIImage imageNamed:@"ic_camera_switch"] forState:UIControlStateNormal];
    [changeButton addTarget:self action:@selector(actionChangeCamera) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:changeButton];
    self.changeButton = changeButton;
    
    //拍照
    UIButton *takePhotoButton = [[UIButton alloc] init];
    [takePhotoButton setImage:[UIImage imageNamed:@"ic_camera_takephoto"] forState:UIControlStateNormal];
    [takePhotoButton setImage:[UIImage imageNamed:@"ic_camera_confirm"] forState:UIControlStateSelected];
    [takePhotoButton addTarget:self action:@selector(actionTakePhoto) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:takePhotoButton];
    self.takePhotoButton = takePhotoButton;
    
    //手电筒
    UIButton *flashlightButton = [[UIButton alloc] init];
    [flashlightButton setImage:[UIImage imageNamed:@"flashlight_normal"] forState:UIControlStateNormal];
    [flashlightButton setImage:[UIImage imageNamed:@"flashlight_selected"] forState:UIControlStateSelected];
    [flashlightButton addTarget:self action:@selector(flashlightAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:flashlightButton];
    self.flashlightButton = flashlightButton;
    
    //相册
    UIButton *albumButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [albumButton setTitle:@"相册上传" forState:UIControlStateNormal];
    [albumButton setTitle:@"" forState:UIControlStateSelected];
    [albumButton setImage:[UIImage imageNamed:@"ic_camera_stop"] forState:UIControlStateSelected];
    [albumButton addTarget:self action:@selector(actionAlbumOrCancel) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:albumButton];
    self.albumButton = albumButton;
    
    
    [self.standardImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(self.view);
        make.height.equalTo(self.view).multipliedBy(0.5);
    }];
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.standardImageView.mas_top);
    }];
    
    [self.outImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(self.contentView);
    }];
    
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(self.view).offset(20);
        make.width.height.mas_equalTo(44);
    }];
    
    [self.changeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.standardImageView).offset(-40);
        make.centerY.mas_equalTo(self.takePhotoButton);
    }];
    
    [self.takePhotoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.standardImageView);
        make.bottom.mas_equalTo(self.standardImageView).offset(-20);
    }];
    
    [self.albumButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.takePhotoButton);
        make.left.mas_equalTo(self.standardImageView).offset(40);
        make.width.equalTo(@100);
    }];
    
    [self.flashlightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.changeButton);
        make.bottom.equalTo(self.changeButton.mas_top).offset(-20);
    }];
}


#pragma mark - 拍照设置
/**获取摄像头*/
- (AVCaptureDevice *)getCameraDeviceWithPosition:(AVCaptureDevicePosition )position{
    NSArray *cameras= [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *camera in cameras) {
        if ([camera position]==position) {
            return camera;
        }
    }
    return nil;
}

/**创建扫描设备*/
- (void)setupCapture
{
    self.session = [[AVCaptureSession alloc] init];
    if ([self.session canSetSessionPreset:AVCaptureSessionPreset1280x720]) {
        self.session.sessionPreset = AVCaptureSessionPreset1280x720;
    }else if ([self.session canSetSessionPreset:AVCaptureSessionPreset1920x1080]){
        self.session.sessionPreset = AVCaptureSessionPreset1920x1080;
    }else if ([self.session canSetSessionPreset:AVCaptureSessionPreset640x480]){
        self.session.sessionPreset = AVCaptureSessionPreset640x480;
    }else if ([self.session canSetSessionPreset:AVCaptureSessionPreset352x288]){
        self.session.sessionPreset = AVCaptureSessionPreset352x288;
    }else if ([self.session canSetSessionPreset:AVCaptureSessionPresetLow]){
        self.session.sessionPreset = AVCaptureSessionPresetLow;
    }
    
//    self.device = [self getCameraDeviceWithPosition:AVCaptureDevicePositionFront]; //默认前置摄像头
    self.device = [self getCameraDeviceWithPosition:AVCaptureDevicePositionBack]; //默认后置摄像头
    
    self.input = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:nil];
    
    //输入设备结合
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    
    self.imageOutput = [[AVCaptureStillImageOutput alloc] init];
    self.imageOutput.outputSettings = @{AVVideoCodecKey:AVVideoCodecJPEG};
    if ([self.session canAddOutput:self.imageOutput]) {
        [self.session addOutput:self.imageOutput];
    }
    
    //预览层的生成
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
//    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspect;
//    self.previewLayer.affineTransform = CGAffineTransformMakeRotation(M_PI * 3/2);
    [self.contentView.layer insertSublayer:self.previewLayer atIndex:0];
    
    //设备取景开始
    [self.session startRunning];
    
    if ([_device lockForConfiguration:nil]) {
        //关闭闪光灯，
        [_device setFlashMode:AVCaptureFlashModeOff];
    }
    
//    if ([_device lockForConfiguration:nil]) {
//        //自动闪光灯，
//        if ([_device isFlashModeSupported:AVCaptureFlashModeAuto]) {
//            [_device setFlashMode:AVCaptureFlashModeAuto];
//        }
//        //自动白平衡,但是好像一直都进不去
//        if ([_device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
//            [_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
//        }
//        [_device unlockForConfiguration];
//    }

}


#pragma mark - action
- (void)actionBack
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

//打开相册 + 取消
- (void)actionAlbumOrCancel
{
    if (self.albumButton.isSelected) {
        //取消当前的预览照片
        self.outImageView.imageModel = nil;
        self.takePhotoButton.selected = NO;
        self.albumButton.selected = NO;
        self.changeButton.hidden = NO;
        self.outImageView.hidden = YES;
        
    }else{
        //打开相册
        WEAKSELF
//        XMAlbumScanController *vc = [[XMAlbumScanController alloc] init];
//        vc.callback = ^(XMAlbumScanModel *scanImageModel) {
//
//            PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
//            options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
//            [[PHImageManager defaultManager] requestImageForAsset:scanImageModel.context targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
//
//                //显示成像的图片
//                XMAlbumScanModel *imageModel = [[XMAlbumScanModel alloc] init];
//                imageModel.imageUrl = nil;
//                imageModel.image = result;
//                weakSelf.outImageView.imageModel = imageModel;
//                weakSelf.outImageView.hidden = NO;
//
//                //设置按钮
//                weakSelf.takePhotoButton.selected = YES;
//                weakSelf.albumButton.selected = YES;
//                weakSelf.changeButton.hidden = YES;
//
//                [weakSelf.navigationController popViewControllerAnimated:YES];
//
//
//
//            }];
        
            
//        };
//        [self.navigationController pushViewController:vc animated:YES];

        if (![AppGlobal isAssetsLibraryAvalable]) {
            return;
        }

        TZImagePickerController *imagePickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:nil];
        imagePickerVC.allowPickingVideo = NO;
        imagePickerVC.allowCrop = NO;
        imagePickerVC.allowPickingGif = NO;
        imagePickerVC.allowPickingOriginalPhoto = NO;
        imagePickerVC.allowPreview = NO;
        
    
        [imagePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            if (photos.count>0) {
                
                UIImage * image = photos[0];
                
                //显示成像的图片
                XMAlbumScanModel *imageModel = [[XMAlbumScanModel alloc] init];
                imageModel.imageUrl = nil;
                imageModel.image = image;
                weakSelf.outImageView.imageModel = imageModel;
                weakSelf.outImageView.hidden = NO;

                //设置按钮
                weakSelf.takePhotoButton.selected = YES;
                weakSelf.albumButton.selected = YES;
                weakSelf.changeButton.hidden = YES;
            }
            
        }];
        [self presentViewController:imagePickerVC animated:YES completion:nil];
    }
}

//切换摄像头
- (void)actionChangeCamera
{
    NSArray *inputs = self.session.inputs;
    for (AVCaptureDeviceInput *input in inputs ) {
        AVCaptureDevice *device = input.device;
        if ( [device hasMediaType:AVMediaTypeVideo] ) {
            AVCaptureDevicePosition position = device.position;
            AVCaptureDevice *newCamera =nil;
            AVCaptureDeviceInput *newInput =nil;
            
            if (position ==AVCaptureDevicePositionFront)
                newCamera = [self getCameraDeviceWithPosition:AVCaptureDevicePositionBack];
            else
                newCamera = [self getCameraDeviceWithPosition:AVCaptureDevicePositionFront];
            
            newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
            
            // beginConfiguration ensures that pending changes are not applied immediately
            [self.session beginConfiguration];
            
            [self.session removeInput:input];
            [self.session addInput:newInput];
            
            // Changes take effect once the outermost commitConfiguration is invoked.
            [self.session commitConfiguration];
            break;
        }
    }
    
}

//手电筒
-(void)flashlightAction:(UIButton *)button{
    
    button.selected = !button.selected;
    
    [self turnTorchOn:button.selected];
}

//拍照 + 确认
- (void)actionTakePhoto
{
    if (self.takePhotoButton.isSelected) {
        //确认照片
        //裁剪图片
        UIImage * image = self.outImageView.imageModel.image;
        CGImageRef  cgimg =  image.CGImage;
        
        CGFloat PicLRmargin =0;
        CGRect rect;
        if (CGImageGetWidth(cgimg) >= CGImageGetHeight(cgimg)) {
            PicLRmargin = (CGImageGetWidth(cgimg)-CGImageGetHeight(cgimg))/2;
            rect =  CGRectMake(PicLRmargin, 0,CGImageGetHeight(cgimg), CGImageGetHeight(cgimg));
        }else{
            PicLRmargin = (CGImageGetHeight(cgimg)-CGImageGetWidth(cgimg))/2;
            rect =  CGRectMake(PicLRmargin, 0,CGImageGetWidth(cgimg), CGImageGetWidth(cgimg));
        }
        
        UIImage * cutImage = [image subImageWithRect:rect];
        if (self.callback) {
            self.callback(cutImage);
        }
        [self dismissViewControllerAnimated:YES completion:nil];

        
    }else{
        
        //拍照
        AVCaptureConnection *connection = [self.imageOutput connectionWithMediaType:AVMediaTypeVideo];
        connection.videoOrientation = AVCaptureVideoOrientationPortrait;
        //成像镜面
        NSArray *inputs = self.session.inputs;
        for (AVCaptureDeviceInput *input in inputs ) {
            AVCaptureDevice *device = input.device;
            if ( [device hasMediaType:AVMediaTypeVideo] ) {
                AVCaptureDevicePosition position = device.position;
                if (position ==AVCaptureDevicePositionFront){
                    connection.videoMirrored = YES;
                }else{
                    connection.videoMirrored = NO;
                }
                break;
            }
        }
        
        // 输出图片
        WEAKSELF
        id takePictureSuccess = ^(CMSampleBufferRef sampleBuffer,NSError *error){
            if (sampleBuffer == NULL) {
                
                
                return ;
            }
            NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:sampleBuffer];
            UIImage *image = [[UIImage alloc]initWithData:imageData];
            
            //图片纠正
            image = [image normalizedImage];
            
            
            //显示成像的图片
            XMAlbumScanModel *imageModel = [[XMAlbumScanModel alloc] init];
            imageModel.imageUrl = nil;
            imageModel.image = image;
            weakSelf.outImageView.imageModel = imageModel;
            weakSelf.outImageView.hidden = NO;
            CGFloat x = 0.5 * (weakSelf.outImageView.contentSize.width - weakSelf.outImageView.app_width);
            weakSelf.outImageView.contentOffset = CGPointMake(x, 0);
            
            
            weakSelf.takePhotoButton.hidden = YES;
            weakSelf.albumButton.hidden = YES;
            weakSelf.changeButton.hidden = YES;
            UIGraphicsBeginImageContextWithOptions(self.contentView.bounds.size, YES, 0);
            [self.contentView drawViewHierarchyInRect:self.contentView.bounds afterScreenUpdates:YES];
            UIImage *snapImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            imageModel.imageUrl = nil;
            imageModel.image = snapImage;
            imageModel.noScale = YES;
            weakSelf.outImageView.imageModel = imageModel;
            weakSelf.outImageView.hidden = NO;
            weakSelf.takePhotoButton.hidden = NO;
            weakSelf.albumButton.hidden = NO;
            weakSelf.changeButton.hidden = NO;
            
            //设置按钮
            weakSelf.takePhotoButton.selected = YES;
            weakSelf.albumButton.selected = YES;
            weakSelf.changeButton.hidden = YES;
            
        };
        [self.imageOutput captureStillImageAsynchronouslyFromConnection:connection completionHandler:takePictureSuccess];
        
    }
}


#pragma mark - 自定义方法

//- (void)addGrid:(UIView *)view {
//    CGFloat widthView = view.bounds.size.width;
//    CGFloat heightView = view.bounds.size.height;
//
//    void (^addLineWidthRect)(CGRect rect) = ^(CGRect rect) {
//        CALayer *layer = [[CAShapeLayer alloc] init];
//        [view.layer addSublayer:layer];
//        layer.frame = rect;
//        layer.backgroundColor = [[UIColor whiteColor] CGColor];
//    };
//
//
//    //画竖线
//    addLineWidthRect(CGRectMake(widthView * 0.5 * 0.5,     0.3 * heightView, 1, heightView * 0.6));
//    addLineWidthRect(CGRectMake(widthView * 0.5 * 0.5 * 3, 0.3 * heightView, 1, heightView * 0.6));
//
//    //画横线
//    addLineWidthRect(CGRectMake(0.3 * heightView * 0.5, heightView * 0.5,                     widthView - 2 * (0.3 * heightView * 0.5), 1));
//    addLineWidthRect(CGRectMake(0.3 * heightView * 0.5, heightView - 0.5 * 0.5 * heightView , widthView - 2 * (0.3 * heightView * 0.5), 1));
//}

- (void)addGrid:(UIView *)view {
    CGFloat widthView = self.view.bounds.size.width;
    CGFloat heightView = self.view.bounds.size.height;
    
    WEAKSELF
    void (^addLineWidthRect)(CGRect rect, BOOL isHori) = ^(CGRect rect, BOOL isHori) {
        CALayer *layer = [[CAShapeLayer alloc] init];
        [view.layer addSublayer:layer];
        layer.frame = rect;
        layer.backgroundColor = [[UIColor clearColor] CGColor];
        
        [weakSelf drawDashLine:layer lineLength:4 lineSpacing:8 lineColor:HEX_RGB(0x333333) lineDirection:isHori];
        
    };
    
    CGFloat baseValue = kScreenHeight/2;
    
    CGFloat startX = (kScreenWidth-kScreenHeight/2)/2;
    
    
    switch (self.angleType) {
            //面部正面
        case CameraAngleTypeFaceFront:
            
            //画竖线
            addLineWidthRect(CGRectMake(startX+baseValue*(900.0/1800.0), 0, 0.8, heightView), NO);
            //画横线
            addLineWidthRect(CGRectMake(0, kScreenHeight*(800.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(1200.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(2605.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(3015.0/3600.0), widthView, 0.8), YES);

            break;
            //面部左侧45度
        case CameraAngleTypeFaceLeft45:
            //画竖线
            addLineWidthRect(CGRectMake(startX+baseValue*(685.0/1800.0), 0, 0.8, heightView), NO);
            addLineWidthRect(CGRectMake(startX+baseValue*(1320.0/1800.0), 0, 0.8, heightView), NO);
            //画横线
            addLineWidthRect(CGRectMake(0, kScreenHeight*(800.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(2610.0/3600.0), widthView, 0.8), YES);
            break;
            
            //面部左侧90度
        case CameraAngleTypeFaceLeft90:
            //画竖线
            addLineWidthRect(CGRectMake(startX+baseValue*(300.0/1800.0), 0, 0.8, heightView), NO);
            addLineWidthRect(CGRectMake(startX+baseValue*(1100.0/1800.0), 0, 0.8, heightView), NO);
            //画横线
//            addLineWidthRect(CGRectMake(0, kScreenHeight*(800.0/3600.0), widthView, 0.8), YES);

            break;
            
            //面部右侧45度
        case CameraAngleTypeFaceRight45:
            //画竖线
            addLineWidthRect(CGRectMake(startX+baseValue*(650.0/1800.0), 0, 0.8, heightView), NO);
            addLineWidthRect(CGRectMake(startX+baseValue*(1300.0/1800.0), 0, 0.8, heightView), NO);
            //画横线
            addLineWidthRect(CGRectMake(0, kScreenHeight*(800.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(2610.0/3600.0), widthView, 0.8), YES);

            break;
            
            //面部右侧90度
        case CameraAngleTypeFaceRight90:
            //画竖线
            addLineWidthRect(CGRectMake(startX+baseValue*(845.0/1800.0), 0, 0.8, heightView), NO);
            addLineWidthRect(CGRectMake(startX+baseValue*(1640.0/1800.0), 0, 0.8, heightView), NO);
            //画横线
//            addLineWidthRect(CGRectMake(0, kScreenHeight*(800.0/3600.0), widthView, 0.8), YES);
            break;
            
            //面部仰角
        case CameraAngleTypeFaceTop:
            //画竖线
            addLineWidthRect(CGRectMake(startX+baseValue*(900.0/1800.0), 0, 0.8, heightView), NO);
            
            //画横线
            addLineWidthRect(CGRectMake(0, kScreenHeight*(640.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(1045.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(2430.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(2840.0/3600.0), widthView, 0.8), YES);
            break;
            
            //身体正面背部
        case CameraAngleTypeBodyfront: case CameraAngleTypeBodyBack:
            //画竖线
            addLineWidthRect(CGRectMake(startX+baseValue*(900.0/1800.0), 0, 0.8, heightView), NO);
            //画横线
            addLineWidthRect(CGRectMake(0, kScreenHeight*(260.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(600.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(1350.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(2070.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(2400.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(3150.0/3600.0), widthView, 0.8), YES);

            break;
            
            //身体左侧45 90 右侧45 90
        case CameraAngleTypeBodyLeft45:case CameraAngleTypeBodyRight45:case CameraAngleTypeBodyLeft90:case CameraAngleTypeBodyRight90:
            //画竖线

            //画横线
            addLineWidthRect(CGRectMake(0, kScreenHeight*(260.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(600.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(1350.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(2070.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(2400.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(3150.0/3600.0), widthView, 0.8), YES);
            
            break;
            
            //自定义
        case CameraAngleTypeNormal:
            //画竖线
            addLineWidthRect(CGRectMake(startX+baseValue*(600.0/1800.0), 0, 0.8, heightView), NO);
            addLineWidthRect(CGRectMake(startX+baseValue*(1200.0/1800.0), 0, 0.8, heightView), NO);
            //画横线
            
            addLineWidthRect(CGRectMake(0, kScreenHeight*(600.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(1200.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(2400.0/3600.0), widthView, 0.8), YES);
            addLineWidthRect(CGRectMake(0, kScreenHeight*(3000.0/3600.0), widthView, 0.8), YES);

            
            break;
            
        default:
            break;
    }
}



- (void)drawDashLine:(CALayer *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor lineDirection:(BOOL)isHorizonal
{
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:lineView.bounds];
    
//    [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame))];
    if (isHorizonal) {
        
        [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame))];
        
    } else{
        [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame)/2)];
    }
    
    [shapeLayer setFillColor:[UIColor clearColor].CGColor];
    
    //  设置虚线颜色为
    [shapeLayer setStrokeColor:lineColor.CGColor];
    
    //  设置虚线宽度
//    [shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)];
    if (isHorizonal) {
        [shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)];
    } else {
        
        [shapeLayer setLineWidth:CGRectGetWidth(lineView.frame)];
    }
    
    [shapeLayer setLineJoin:kCALineJoinRound];
    
    //  设置线宽，线间距
    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];
    
    //  设置路径
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);
    
    if (isHorizonal) {
        CGPathAddLineToPoint(path, NULL, CGRectGetWidth(lineView.frame), 0);
    }else{
        CGPathAddLineToPoint(path, NULL, 0, CGRectGetHeight(lineView.frame));
    }
    
    [shapeLayer setPath:path];
    CGPathRelease(path);
    
    //  把绘制好的虚线添加上来
    [lineView addSublayer:shapeLayer];
}

//开关手电筒
-(void)turnTorchOn: (bool) on
{
    Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
    
    if (captureDeviceClass !=nil) {
        
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        
        if ([device hasTorch] && [device hasFlash]){
            
            [device lockForConfiguration:nil];
            
            if (on) {
                [device setTorchMode:AVCaptureTorchModeOn];
            } else {
                [device setTorchMode:AVCaptureTorchModeOff];
            }
            [device unlockForConfiguration];
        }else{
            NSLog(@"初始化失败");
        }
    }else{
        NSLog(@"没有闪光设备");
    }
}

-(void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    [[SDImageCache sharedImageCache]clearMemory];

}


@end
